package REMC.replicaExchange;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import REMC.objects.MyLogger;
/**
 * @authors Tal & Adiel
 * this class is used to collect the statistics for each temperature in the cVec vector
 * in the replica exchange algorithm.
 */

public class ReplicaStatisticsHandler {
	
	private FileWriter fileWriter;
	private Map<Integer, Integer> countOccur;
	private double temperature;
	
	/**
	 * constractor
	 * @param temp - the temperature of the replica this object is assigned to. 
	 */
	public ReplicaStatisticsHandler(double temp){
		try {
			MyLogger.getLogger().Log("Openning stats file: " + "REMC_Temp" + temp + ".csv");
			fileWriter = new FileWriter("REMC_Temp" + temp + ".csv", false);
		} catch (IOException e) {
			MyLogger.getLogger().Log("Couldn't open stats file: " + "REMC_Temp" + temp + ".csv" + "\n" + e.getMessage());
			e.printStackTrace();
		}
		countOccur = new HashMap<Integer, Integer>();
		this.temperature = temp;
	}
	
	/**
	 * writing the results that collected to a file 
	 */
	public void writeResultsToFile() {
			//for getting data for a single monte carlo search
			MyLogger.getLogger().Log("Going to write Stats for Temp: " + this.temperature);
			try {
				for (Iterator<Integer> iterator = countOccur.keySet().iterator(); iterator
						.hasNext();) {
					Integer fitness = (Integer) iterator.next();
					fileWriter.write(fitness+","+countOccur.get(fitness)+"\n");
				}
				MyLogger.getLogger().Log("Finished to writing Stats for Temp: " + this.temperature);
				fileWriter.close();
				MyLogger.getLogger().Log("Closed Stats File for Temp: " + this.temperature);
			} catch (IOException e) {
				MyLogger.getLogger().Log("Got an exception while writing stats to file Temp: " + this.temperature + e.getMessage());
				e.printStackTrace();
			}
		}

	/**
	 * adding the fitness to the fitness count 
	 * @param fitness to add to the data
	 */
	public void addStat(int fitness) {
		//adding fitness to HashMap
		if (countOccur.containsKey(fitness)){
			countOccur.put(fitness, countOccur.get(fitness)+1);
		}else{
			countOccur.put(fitness, 1);
		}
	}

	public void writeTempResultsToLogger(int loopNumber) {
		
		String ans = "Iteration: " + loopNumber + " Temporary results for temp: " + this.temperature + "\n";
		for (Iterator<Integer> iterator = countOccur.keySet().iterator(); iterator
				.hasNext();) {
			Integer key = (Integer) iterator.next();
			ans = ans + key+ ","+countOccur.get(key)+"\n";
		}
		MyLogger.getLogger().Log(ans);
		
	}

}
